package com.jake.xpage.demos.applemusic;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;

import com.jake.xpage.R;
import com.jake.xpage.demos.applemusic.pages.AMBroadcastPage;
import com.jake.xpage.demos.applemusic.pages.AMDiscoverPage;
import com.jake.xpage.demos.applemusic.pages.AMMainPage;
import com.jake.xpage.demos.applemusic.pages.AMResourcePage;
import com.jake.xpage.demos.applemusic.pages.AMSearchPage;
import com.jake.xpage.page.XPage;
import com.jake.xpage.page.XPageConfig;
import com.jake.xpage.page.XPageContainer;

public class AppleMusicMainPage extends XPage {
    private FrameLayout mContentLayout;
    private RadioGroup mRgToolbar;
    private SparseArray<XPageContainer> mPageContainers = new SparseArray<>();
    private int mCurrentTabId = R.id.rb_home;

    public AppleMusicMainPage(@NonNull Context context) {
        super(context);
        LayoutInflater.from(getContext()).inflate(R.layout.page_apple_music, this);
        mContentLayout = findViewById(R.id.fl_content);
        mRgToolbar = findViewById(R.id.rg_toolbar);
        initPageContainers();
        mRgToolbar.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                mCurrentTabId = checkedId;
                XPageContainer container = mPageContainers.get(checkedId);
                mContentLayout.removeAllViews();
                mContentLayout.addView(container, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                AppMusicNavigator.switchContainer(container);
            }
        });
        mRgToolbar.check(mCurrentTabId);
    }


    private void initPageContainers() {
        mPageContainers.put(R.id.rb_home, generatePageContainer(new AMMainPage(getContext())));
        mPageContainers.put(R.id.rb_discover, generatePageContainer(new AMDiscoverPage(getContext())));
        mPageContainers.put(R.id.rb_broadcast, generatePageContainer(new AMBroadcastPage(getContext())));
        mPageContainers.put(R.id.rb_resource, generatePageContainer(new AMResourcePage(getContext())));
        mPageContainers.put(R.id.rb_search, generatePageContainer(new AMSearchPage(getContext())));
    }

    private XPageContainer generatePageContainer(@NonNull XPage rootPage) {
        XPageContainer container = new XPageContainer(rootPage);
        getLifecycle().addObserver(container.getLifecycleObserver());
        container.setHost(new XPageContainer.IHost() {
            @Override
            public void closeContainer() {
                finish();
            }
        });
        return container;
    }

    @Override
    public boolean onBackPressed() {
        return mPageContainers.get(mCurrentTabId).onBackPressed();
    }
}
